import { createRouter, createWebHistory } from 'vue-router'
import { defineAsyncComponent } from 'vue'
// import Home from "@/views/home/index.vue"
import Login from "@/views/login/index.vue"
import Publishingresources from "@/views/resources/publishing/index.vue"
// 假设你有一个方法来检查用户是否已认证
function isAuthenticated() {
  // 这里你可以添加实际的认证逻辑，比如检查token或登录状态
  return !!localStorage.getItem('userInfo');
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import("@/views/home/index.vue")
    },
    {
      path: '/login',
      name: 'login',
      component:  Login
    },
    {
      path: '/myresources',
      name: 'myresources',
      component: () => import("@/views/resources/my/index.vue")
    },
    {
      path: '/publishingresources',
      name: 'publishingresources',
      component: Publishingresources,
    },
    {
      path: '/allresources',
      name: 'allresources',
      component: () => import("@/views/resources/allresources/index.vue")
    },
    {
      path: '/withdrawal',
      name: 'withdrawal',
      component: defineAsyncComponent(() => import("@/views/order/withdrawal/index.vue"))
    },
    {
      path: '/recharge',
      name: 'recharge',
      component: defineAsyncComponent(() => import("@/views/order/recharge/index.vue"))
    },
    {
      path: "/feedback",
      name: 'feedback',
      component: () => import("@/views/feedback/index.vue"),
    },
    {
      path: "/personalcenter",
      name: 'personalcenter',
      component: defineAsyncComponent(() => import("@/views/personalCenter/index.vue")),
    },
    { path:'/editresources',
      name: 'editresources',
      component: () => import("@/views/resources/editresources/index.vue")
    },
    { path:'/detail',
      name: 'detail',
      component: () => import("@/views/resources/detail/index.vue"),
    },
    {
      path: "/404",
      component: () => import('@/views/state/404.vue')
    },
    {
      path: "/success",
      component: () => import('@/views/state/success.vue')
    },
    {
      path: "/search",
      component: () => import('@/views/search/index.vue')
    },
    {
      path: "/:catchAll(.*)",
      redirect: '/404',

    }
    
  ]
})
 // 添加导航守卫
router.beforeEach((to, from, next) => {
  if(to.name === 'login'){
    localStorage.removeItem('userInfo');
  }
  // 检查路由是否需要认证
  if (to.name !== 'login' && !isAuthenticated()) {
    // 如果用户未认证，重定向到登录页面
    next({ name: 'login' });
  } else {
    // 否则，允许路由导航
    next();
  }
});
export default router
